package com.struts;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * xml解析
 */
public class XmlParser {

	@SuppressWarnings("unchecked")
	public static Map<String, ActionBean> parser(String url) {
		Map<String, ActionBean> xmlBeanMap = null;
		SAXReader sax = null;
		Document document = null;
		ActionBean actionBean = null;
		try {
			sax = new SAXReader();
			document = sax.read(url);
			xmlBeanMap = new HashMap<String, ActionBean>();

			Element root = document.getRootElement();

			Element formbeans = root.element("formbeans");
			List<Element> formbeanList = formbeans.elements();

			Element actions = root.element("actions");
			List<Element> actionList = actions.elements();
			for (Element action : actionList) {
				actionBean = new ActionBean();
				String name = action.attributeValue("name");
				String clazz = action.attributeValue("class");
				String path = action.attributeValue("path");

				List<Element> resultList = action.elements("result");
				Map<String, String> resultMap = new HashMap<String, String>();

				for (Element result : resultList) {
					resultMap.put(result.attributeValue("name"), result.getText());
				}

				actionBean.setName(name);
				actionBean.setPath(path);
				actionBean.setActionClass(clazz);
				actionBean.setResultMap(resultMap);

				for (Element formbean : formbeanList) {
					if (formbean.attributeValue("name").equals(name)) {
						actionBean.setFormClass(formbean.attributeValue("class"));
						break;
					}
				}
				xmlBeanMap.put(path, actionBean);
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return xmlBeanMap;
	}
}
